package com.dqp.cslggroup.SubjectView;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.preference.PreferenceManager;
import com.dqp.cslggroup.EventBus.MessageEvent;
import com.dqp.cslggroup.MainActivity;
import com.dqp.cslggroup.R;
import com.dqp.cslggroup.UI.DialogView;
import com.zhuangfei.timetable.TimetableView;
import com.zhuangfei.timetable.listener.ISchedule;
import com.zhuangfei.timetable.listener.OnSlideBuildAdapter;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;

public class SubjectFragmentLazyLoad extends Fragment {
    private TimetableView mTimetableView;
    private Context context;
    private int week;
    private View view;
    private SharedPreferences sp;
    private SharedPreferences.Editor editor;
    private boolean showWeekends;
    private boolean isThisWeek;
    private boolean showTime;
    private int length;
    private int jie;
    private int transparency;
    private int timeSize;
    private String[] times = new String[]{
            "08:00\n08:50", "09:00\n09:50",
            "10:10\n11:00", "11:10\n12:00",
            "13:30\n14:20", "14:30\n15:20",
            "15:40\n16:30", "16:40\n17:30",
            "18:30\n19:20", "19:30\n20:20",
            "20:40\n21:30", "21:40\n22:30",
            "22:40\n23:30", "23:40\n00:30",
    };
    private Handler handler = new Handler();
    private boolean couples = true;

    @SuppressLint("InflateParams")
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.timetable_view, container, false);
        context = view.getContext();
        mTimetableView = view.findViewById(R.id.id_timetableView);
        EventBus.getDefault().register(this);
        initTimetableView();
        return view;
    }

   /* @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if ( isVisibleToUser) {
            week = ((MainActivity)context).toValue();
            couples=((MainActivity)context).toCouples();
            initTimetableView(week,couples);
        }
    }*/

    private void PreferenceManagerDate() {
        sp = PreferenceManager.getDefaultSharedPreferences(context);
        editor = sp.edit();
        showWeekends = sp.getBoolean("showWeekends", true);
        isThisWeek = sp.getBoolean("show", false);
        length = sp.getInt("lattice_length", 180);
        jie = sp.getInt("course_jie", 10);
        transparency = sp.getInt("transparency", 3);
        showTime = sp.getBoolean("showTime", true);
        timeSize = sp.getInt("timeSize", 8);
        editor.apply();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MessageEvent event) {
        if (event.getEvent().equals("SubjectFragment")) {
            if (event.getRefresh() != null && event.getRefresh())
                refreshTimeTableView();
            if (event.getWhat() == 1) {
                refreshCouplesTimeTableView();
                couples = false;
            }

            if (event.getWhat() == 2) {
                couples = true;
                refreshTimeTableView();
            }


        }
        if (event.getEvent().equals("SubjectFragmentLazyLoad")) {
            if (event.getWhat() == 66) {
                week = ((MainActivity) context).toValue();
                couples = ((MainActivity) context).toCouples();
                handler.postDelayed(() -> initTimetableView(week, couples), 500);
            }
        }
    }

    /**
     * 初始化课程控件
     */
    private void initTimetableView() {
        PreferenceManagerDate();
        mTimetableView
                .maxSlideItem(jie)
                .monthWidthDp(25)
                .itemHeight(length)
                .itemTextColor(Color.WHITE, true)
                .isShowNotCurWeek(isThisWeek)
                .cornerAll(15)
                .isShowWeekends(showWeekends)
                .isShowFlaglayout(false)
                .alpha(0f, 0f, transparency * 0.1f)
                .showView();
        if (showTime) showTime(timeSize * 1f);
        else hideTime();

    }

    private void refreshCouplesTimeTableView() {
        PreferenceManagerDate();
        List<MySubject> mySubjects = SubjectRepertory.loadCouplesSubjects();
        mTimetableView
                .source(mySubjects)
                .isShowNotCurWeek(isThisWeek)
                .itemHeight(length)
                .isShowWeekends(showWeekends)
                .maxSlideItem(jie)
                .alpha(0f, 0f, transparency * 0.1f)
                .updateView();
        if (showTime) showTime(timeSize * 1f);
        else hideTime();

    }


    /**
     * 刷新课程控件数据
     */
    private void initTimetableView(int week, boolean couples) {
        List<MySubject> mySubjects;
        if (couples)
            mySubjects = SubjectRepertory.loadSubjects();
        else mySubjects = SubjectRepertory.loadCouplesSubjects();
        mTimetableView.curWeek(week)
                .source(mySubjects)
                .callback((ISchedule.OnItemClickListener) (v, scheduleList) -> DialogView.courseMore(context, scheduleList, week, couples, () -> {
                    if (couples) refreshTimeTableView();
                    else refreshCouplesTimeTableView();
                }))
                .updateView();
    }

    private void refreshTimeTableView() {
        PreferenceManagerDate();
        List<MySubject> mySubjects = SubjectRepertory.loadSubjects();
        mTimetableView.curWeek(week)
                .source(mySubjects)
                .maxSlideItem(jie)
                .monthWidthDp(25)
                .itemHeight(length)
                .itemTextColor(Color.WHITE, true)
                .isShowNotCurWeek(isThisWeek)
                .cornerAll(15)
                .isShowWeekends(showWeekends)
                .isShowFlaglayout(false)
                .alpha(0f, 0f, transparency * 0.1f)
                .updateView();
        if (showTime) showTime(timeSize * 1f);
        else hideTime();

    }

    /**
     * 显示时间
     * 设置侧边栏构建监听，TimeSlideAdapter是控件实现的可显示时间的侧边栏
     */
    private void showTime(float size) {
        OnSlideBuildAdapter listener = (OnSlideBuildAdapter) mTimetableView.onSlideBuildListener();
        listener.setTimes(times)
                .setTimeTextSize(size);
        mTimetableView.updateSlideView();
    }


    private void hideTime() {
        mTimetableView.callback((ISchedule.OnSlideBuildListener) null);
        mTimetableView.updateSlideView();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);

    }

}

